/*
 * 描述： IP拦截自定义全局过滤器
 * 修改人： Weng.weng
 * 修改时间： 2020年10月22日
 * 项目： gateway-server
 */
package com.tuozixuan.filter;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * IP拦截自定义全局过滤器<br>
 * 
 * @author Weng.weng
 * @version [版本号, 2020年10月22日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
public class IpCheckGlobalFilter implements GlobalFilter, Ordered {
    
    @Override
    public int getOrder() {
        return 0;
    }
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        
        HttpHeaders httpHeaders = exchange.getRequest().getHeaders();
        List<String> ipBlackList = new ArrayList<>(); // TODO 获取IP黑名单
        String ip = "127.0.0.1"; // from header
        if (ipBlackList.contains(ip)) {
            ServerHttpResponse response = exchange.getResponse();
            byte[] datas = null; // JSON格式字符串字节数组
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        
        return chain.filter(exchange);
    }
    
}
